// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
import * as fs from 'fs';
import * as path from 'path';

// This method is called when your extension is activated
// Your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {

	// Use the console to output diagnostic information (console.log) and errors (console.error)
	// This line of code will only be executed once when your extension is activated
	console.log('Congratulations, your extension "auto-nvm" is now active!');

	// 监听终端创建事件
	const terminalDisposable = vscode.window.onDidOpenTerminal(async (terminal) => {
		console.log('新终端已创建:', terminal.name);
		
		// 检查工作区是否存在
		if (!vscode.workspace.workspaceFolders || vscode.workspace.workspaceFolders.length === 0) {
			console.log('没有打开的工作区');
			return;
		}

		// 获取工作区根目录
		const workspaceRoot = vscode.workspace.workspaceFolders[0].uri.fsPath;
		const nvmrcPath = path.join(workspaceRoot, '.nvmrc');

		// 检查 .nvmrc 文件是否存在
		try {
			if (fs.existsSync(nvmrcPath)) {
				console.log('发现 .nvmrc 文件，执行 nvm use');
				
				// 稍等一下让终端完全初始化
				setTimeout(() => {
					// 在终端中执行 nvm use 命令
					terminal.sendText('nvm use');
				}, 500);
			} else {
				console.log('未找到 .nvmrc 文件，跳过 nvm use');
			}
		} catch (error) {
			console.error('检查 .nvmrc 文件时出错:', error);
		}
	});

	// The command has been defined in the package.json file
	// Now provide the implementation of the command with registerCommand
	// The commandId parameter must match the command field in package.json
	const disposable = vscode.commands.registerCommand('auto-nvm.helloWorld', () => {
		// The code you place here will be executed every time your command is executed
		// Display a message box to the user
		vscode.window.showInformationMessage('Hello World from auto-nvm!');
	});

	context.subscriptions.push(disposable);
	context.subscriptions.push(terminalDisposable);
}

// This method is called when your extension is deactivated
export function deactivate() {}
